﻿using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geometry;
using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using ESRI.ArcGIS.esriSystem;
//using ESRI.ArcGIS.SpatialAnalyst;
using ESRI.ArcGIS.GeoAnalyst;

namespace School
{
    public partial class AttributeSelectionForm : Form
    {
        private AxMapControl _mapControl;
        private IFeatureLayer _featureLayer;
        private System.Windows.Forms.Button btnCancelSelection;

        public AttributeSelectionForm(AxMapControl mapControl)
        {
            InitializeComponent();
            _mapControl = mapControl;
        }

        private void AttributeQueryForm_Load(object sender, EventArgs e)
        {
            if (_mapControl.LayerCount <= 0)
            {
                MessageBox.Show("地图中没有图层！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.Close(); // 关闭当前属性查询窗体
                return;
            }

            cboLayer.Items.Clear();
            for (int i = 0; i < _mapControl.LayerCount; i++)
            {
                ILayer layer = _mapControl.get_Layer(i);
                cboLayer.Items.Add(layer.Name);
            }

            if (cboLayer.Items.Count > 0)
                cboLayer.SelectedIndex = 0;
        }

        private void cboLayer_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cboLayer.SelectedIndex < 0)
                return;

            ILayer layer = _mapControl.get_Layer(cboLayer.SelectedIndex);
            _featureLayer = layer as IFeatureLayer;

            if (_featureLayer == null)
            {
                MessageBox.Show("选中的图层不是要素图层，请重新选择！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
        }

        private void btnBuildExpression_Click(object sender, EventArgs e)
        {
            if (_featureLayer == null)
            {
                MessageBox.Show("请先选择一个要素图层！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            using (QueryBuilderForm form = new QueryBuilderForm(_featureLayer))
            {
                if (form.ShowDialog() == DialogResult.OK)
                {
                    txtExpression.Text = form.BuiltExpression;
                }
            }
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            try
            {
                if (_featureLayer == null)
                {
                    MessageBox.Show("请先选择一个要素图层！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                if (string.IsNullOrEmpty(txtExpression.Text))
                {
                    MessageBox.Show("请输入查询表达式！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                IQueryFilter queryFilter = new QueryFilter();
                queryFilter.WhereClause = txtExpression.Text;

                _mapControl.Map.ClearSelection();

                int featureCount = 0;
                IFeatureClass featureClass = _featureLayer.FeatureClass;

                if (featureClass == null)
                {
                    MessageBox.Show("无法获取要素类，请检查图层！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                IFeatureCursor featureCursor = null;
                try
                {
                    featureCursor = featureClass.Search(queryFilter, false);

                    if (featureCursor == null)
                    {
                        MessageBox.Show("查询游标为空，可能是表达式语法错误！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }

                    IFeature feature;
                    while ((feature = featureCursor.NextFeature()) != null)
                    {
                        _mapControl.Map.SelectFeature(_featureLayer, feature);
                        featureCount++;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"查询过程中发生错误：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                finally
                {
                    if (featureCursor != null)
                    {
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(featureCursor);
                        featureCursor = null;
                    }
                }

                // 刷新地图以显示选择
                _mapControl.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeoSelection, null, null);

                if (featureCount > 0)
                {
                    // 获取选择集并计算其包围盒
                    IFeatureSelection featureSelection = _featureLayer as IFeatureSelection;
                    if (featureSelection != null)
                    {
                        ISelectionSet selectionSet = featureSelection.SelectionSet;
                        if (selectionSet != null)
                        {
                            IEnvelope selectionEnv = new EnvelopeClass();
                            IEnumIDs enumIDs = selectionSet.IDs;
                            int id;
                            while ((id = enumIDs.Next()) != -1)
                            {
                                IFeature feature = _featureLayer.FeatureClass.GetFeature(id);
                                if (feature != null)
                                {
                                    selectionEnv.Union(feature.Shape.Envelope);

                                    // 计算并输出选中要素的面积
                                    if (feature.Shape.GeometryType == esriGeometryType.esriGeometryPolygon)
                                    {
                                        IArea area = (IArea)feature.Shape;
                                        double areaValue = area.Area;
                                        txtLog.AppendText($"要素 ID: {feature.OID}, 面积: {areaValue:N2} 平方米" + Environment.NewLine);
                                    }
                                }
                            }

                            if (!selectionEnv.IsEmpty)
                            {
                                selectionEnv.Expand(1.2, 1.2, false);
                                _mapControl.Extent = selectionEnv;
                                _mapControl.ActiveView.Refresh();
                            }

                            // 释放COM对象
                            if (enumIDs != null)
                                System.Runtime.InteropServices.Marshal.ReleaseComObject(enumIDs);
                        }
                    }
                    MessageBox.Show($"共找到 {featureCount} 个匹配的要素！", "查询结果", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show("未找到匹配的要素！", "查询结果", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"执行查询时发生未知错误：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnCancelSelection_Click(object sender, EventArgs e)
        {
            try
            {
                // 清除所有图层的选择
                for (int i = 0; i < _mapControl.LayerCount; i++)
                {
                    ILayer layer = _mapControl.get_Layer(i);
                    if (layer is IFeatureLayer featureLayer)
                    {
                        IFeatureSelection featureSelection = featureLayer as IFeatureSelection;
                        if (featureSelection != null)
                        {
                            featureSelection.Clear();
                        }
                    }
                }

                // 刷新地图以确保选择集被清除
                _mapControl.ActiveView.Refresh();
                _mapControl.Invalidate();

                MessageBox.Show("已取消选择！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"取消选择时发生错误：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}